package com.goldplusgold.tradedelay.app.market.fragment;


import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.goldplusgold.network.lib.exception.ServerException;
import com.goldplusgold.network.lib.http.protobuf.Market;
import com.goldplusgold.support.lib.base.fragment.BaseFragment;
import com.goldplusgold.support.lib.utils.MathUtils;
import com.goldplusgold.support.lib.utils.NetWorkConstant;
import com.goldplusgold.support.lib.utils.StringConvertNumber;
import com.goldplusgold.support.lib.widget.AsyncTask;
import com.goldplusgold.tradedelay.app.R;
import com.goldplusgold.tradedelay.app.base.constant.IntentConstant;
import com.goldplusgold.tradedelay.app.base.utils.ActivityUtils;
import com.goldplusgold.tradedelay.app.home.pojo.TDLogin;
import com.goldplusgold.tradedelay.app.home.serivce.HomeService;
import com.goldplusgold.tradedelay.app.main.activity.TDMainActivity;
import com.goldplusgold.tradedelay.app.market.MarketManager;
import com.goldplusgold.tradedelay.app.market.eventbus.ConnectionFailEvent;
import com.goldplusgold.tradedelay.app.market.eventbus.ConnectionSuccessEvent;
import com.goldplusgold.tradedelay.app.market.eventbus.DynaMessageEvent;
import com.goldplusgold.tradedelay.app.market.eventbus.FiveRangeMessageEvent;
import com.goldplusgold.tradedelay.app.market.eventbus.InstMessageEvent;
import com.goldplusgold.tradedelay.app.market.pojo.CMinute;
import com.goldplusgold.tradedelay.app.market.pojo.FenshiDataResponse;
import com.goldplusgold.tradedelay.app.market.pojo.FenshiParam;
import com.goldplusgold.tradedelay.app.market.pojo.StickData;
import com.goldplusgold.tradedelay.app.market.widget.chartview.CrossView;
import com.goldplusgold.tradedelay.app.market.widget.chartview.FenshiView;
import com.goldplusgold.tradedelay.app.market.widget.chartview.KLineView;
import com.goldplusgold.tradedelay.app.my.activity.UserActivity;
import com.goldplusgold.tradedelay.app.my.networkservice.MyService;
import com.goldplusgold.tradedelay.app.trade.networkservice.TradeService;
import com.goldplusgold.tradedelay.app.trade.pojo.Switch;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class QuotationChartFragment extends BaseFragment implements MarketManager.StickReceiver , MarketManager.MinuteReceiver {

    private static final String QUOTATION_INS_TYPE_KEY = "quotation_ins_type_key";
    @BindView(R.id.current_price)
    TextView currentPrice;
    @BindView(R.id.txt_rate)
    TextView txtRate;
    @BindView(R.id.txt_current_time)
    TextView txtCurrentTime;
    @BindView(R.id.current_trade_state)
    TextView currentTradeState;
    @BindView(R.id.highest_price)
    TextView highestPrice;
    @BindView(R.id.minimum_price)
    TextView minimumPrice;
    @BindView(R.id.yesterday_close_price)
    TextView yesterdayClosePrice;
    @BindView(R.id.yesterday_end_price)
    TextView yesterdayEndPrice;
    @BindView(R.id.today_open_price)
    TextView todayOpenPrice;
    @BindView(R.id.total_quantity)
    TextView totalQuantity;
    @BindView(R.id.txt_time)
    TextView txtTime;
    @BindView(R.id.txt_kday)
    TextView txtKday;
    @BindView(R.id.tv_kweek)
    TextView tvKweek;
    @BindView(R.id.txt_kmonth)
    TextView txtKmonth;
    @BindView(R.id.txt_kminute)
    TextView txtKminute;
    @BindView(R.id.kminute_layout)
    LinearLayout kminuteLayout;
    @BindView(R.id.iv_time_line)
    ImageView ivTimeLine;
    @BindView(R.id.iv_kday_line)
    ImageView ivKdayLine;
    @BindView(R.id.iv_kweek_line)
    ImageView ivKweekLine;
    @BindView(R.id.iv_kmonth_line)
    ImageView ivKmonthLine;
    @BindView(R.id.iv_kminute_line)
    ImageView ivKminuteLine;
    @BindView(R.id.btn_complete)
    Button btnComplete;
    @BindView(R.id.main_fragment)
    FrameLayout mainFragment;
    @BindView(R.id.minute_data_layout)
    LinearLayout minuteDataLayout;
    @BindView(R.id.kLine_data_layout)
    LinearLayout kLineDataLayout;
    @BindView(R.id.vp_title_layout)
    LinearLayout vpTitleLayout;
    @BindView(R.id.minute_time)
    TextView minuteTime;
    @BindView(R.id.minute_price_rate)
    TextView minutePriceRate;
    @BindView(R.id.minute_volume)
    TextView minuteVolume;
    @BindView(R.id.open_price)
    TextView openPrice;
    @BindView(R.id.khighest_price)
    TextView khighestPrice;
    @BindView(R.id.krate)
    TextView kRate;
    @BindView(R.id.k_volume)
    TextView kVolume;
    @BindView(R.id.close_price)
    TextView closePrice;
    @BindView(R.id.klowest_price)
    TextView klowestPrice;
    @BindView(R.id.kquota)
    TextView kquota;
    @BindView(R.id.average_price)
    TextView averagePrice;
    @BindView(R.id.minute_average_price)
    TextView minuteAveragePrice;
    @BindView(R.id.tip_layout)
    RelativeLayout tipLayout;

    @BindView(R.id.k_cff_msg)
    TextView kmsgText;
    @BindView(R.id.ckf_klineview)
    KLineView mKLineView;
    @BindView(R.id.k_cff_cross)
    CrossView kcrossView;


    @BindView(R.id.sold_five)
    TextView soldFive;
    @BindView(R.id.sold_five_volume)
    TextView soldFiveVolume;
    @BindView(R.id.sold_four)
    TextView soldFour;
    @BindView(R.id.sold_four_volume)
    TextView soldFourVolume;
    @BindView(R.id.sold_three)
    TextView soldThree;
    @BindView(R.id.sold_three_volume)
    TextView soldThreeVolume;
    @BindView(R.id.sold_two)
    TextView soldTwo;
    @BindView(R.id.sold_two_volume)
    TextView soldTwoVolume;
    @BindView(R.id.sold_one)
    TextView soldOne;
    @BindView(R.id.sold_one_volume)
    TextView soldOneVolume;
    @BindView(R.id.buy_one)
    TextView buyOne;
    @BindView(R.id.buy_one_volume)
    TextView buyOneVolume;
    @BindView(R.id.buy_two)
    TextView buyTwo;
    @BindView(R.id.buy_two_volume)
    TextView buyTwoVolume;
    @BindView(R.id.buy_three)
    TextView buyThree;
    @BindView(R.id.buy_three_volume)
    TextView buyThreeVolume;
    @BindView(R.id.buy_four)
    TextView buyFour;
    @BindView(R.id.buy_four_volume)
    TextView buyFourVolume;
    @BindView(R.id.buy_five)
    TextView buyFive;
    @BindView(R.id.buy_five_volume)
    TextView buyFiveVolume;
    @BindView(R.id.cff_fenshiview)
    FenshiView fenshiView;
    @BindView(R.id.cff_cross)
    CrossView crossView;
    //滑动十字线时，显示对应点详情的地方
    @BindView(R.id.cff_msg)
    TextView msgText;


    @BindView(R.id.chart_minute_view)
    View charMinuteView ;
    @BindView(R.id.chart_kline_view)
    View chartKlineView ;


    ImageView[] lines ;

    private Market.InstType instType;
    private int prePosition = 0;
    private PopupWindow popupWindow;
    private LinearLayout layout;
    private LinearLayout stateTipLayout;
    private ListView lvPopup;
    private boolean tradeState;
    private KLineFragment kMinuteChartFragment;
    FenshiDataResponse minuteData = new FenshiDataResponse();
    private double yesterdayClosingPrice;
    private final MyHandler handler = new MyHandler(this);
    int cur_id = -1;

    private Market.Category mCategory;

    public static QuotationChartFragment newInstance(Market.InstType param1) {
        QuotationChartFragment fragment = new QuotationChartFragment();
        Bundle args = new Bundle();
        args.putSerializable(QUOTATION_INS_TYPE_KEY, param1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();
        if (args != null && !args.isEmpty()) {
            instType = (Market.InstType) args.getSerializable(QUOTATION_INS_TYPE_KEY);
        }
    }

    @Override
    protected void initView() {
        super.initView();
        lines = new ImageView[]{ivTimeLine , ivKdayLine , ivKweekLine ,ivKmonthLine , ivKminuteLine};
        //初始默认为0
        selectTab(0);
    }

    @Override
    public void onResume() {
        super.onResume();
        if(!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        MarketManager.getInstance().setStickReceiver(this);
        MarketManager.getInstance().setMinuteReceiver(this);
        MarketManager.getInstance().sendRequestMsg(instType);
    }

    @Override
    public void onStop() {
        super.onStop();
        MarketManager.getInstance().setStickReceiver(null);
        MarketManager.getInstance().setMinuteReceiver(null);
        EventBus.getDefault().unregister(this);
    }

    public void changeType(Market.InstType instType){
        if(this.instType == instType){
            return;
        }
        this.instType = instType;
        changeAndSend(cur_id);
    }

    @OnClick({R.id.txt_time,R.id.txt_kday,R.id.tv_kweek,R.id.txt_kmonth,R.id.txt_kminute})
    public void onViewClicked(View view) {
        switch (view.getId()){
            case R.id.txt_time:
                selectTab(0);
                break;
            case R.id.txt_kday:
                selectTab(1);
                break;
            case R.id.tv_kweek:
                selectTab(2);
                break;
            case R.id.txt_kmonth:
                selectTab(3);
                break;
            case R.id.txt_kminute:
                selectTab(4);
                break;
        }
    }


    public void selectTab(int position){
        if(position == 0){
            charMinuteView.setVisibility(View.VISIBLE);
            chartKlineView.setVisibility(View.GONE);
        }else{
            chartKlineView.setVisibility(View.VISIBLE);
            charMinuteView.setVisibility(View.GONE);
        }
        for(int i = 0 ; i < lines.length ; i++){
            if(i == position){
                lines[i].setBackgroundColor(getActivity().getResources().getColor(R.color.color_gold));
            }else{
                lines[i].setBackgroundColor(getActivity().getResources().getColor(R.color.color_white));
            }
        }
        changeAndSend(position);
    }

    private void changeAndSend(int id){
        if(id == -1){
           return;
        }
        cur_id = id;
        switch (id){
            case 0:
                MarketManager.getInstance().sendRequestMsg(this.instType);
                break;
            case 1:
                MarketManager.getInstance().sendRequestMsg(this.instType,Market.Category.KLINEDAYPAGE);
                break;
            case 2:
                MarketManager.getInstance().sendRequestMsg(this.instType,Market.Category.KLINEWEEKPAGE);
                break;
            case 3:
                MarketManager.getInstance().sendRequestMsg(this.instType,Market.Category.KLINEMONTHPAGE);
                break;
            case 4:
                MarketManager.getInstance().sendRequestMsg(this.instType,Market.Category.KLINEMIN1PAGE);
                break;
            default:
                break;
        }

    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_tdquotation_chart;
    }


    @OnClick({R.id.current_trade_state, R.id.kminute_layout, R.id.btn_complete})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.current_trade_state:
                if (tradeState) {
                    showStateTipView("可进行延期开平仓交易");
                } else {
                    showStateTipView("不可进行延期开平仓交易");
                }
                break;
            case R.id.kminute_layout:
                showMorePopupWindow();
                ActivityUtils.backgroundAlpha(getActivity(), 0.5f);
                break;
            case R.id.btn_complete:
                new QuerySwitchStateTask().execute(AsyncTask.TYPE_NET);
                break;
        }
    }

    //分时的（日K，  周k ， yue k , 分钟）
    @Override
    public void onReceive(final List<StickData> list) {
        Log.e("hurui" , "StikckData : " + list.size());
        if(mKLineView != null && mKLineView.getVisibility() == View.VISIBLE){
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mKLineView.setDataAndInvalidate(list,instType);
                    mKLineView.setUsedViews(kcrossView , msgText);
                    mKLineView.setOnCrossListener(new KLineView.OnCrossListener() {
                        @Override
                        public void onDismiss() {
                            hideKLineTitle();
                        }

                        @Override
                        public void onShow(StickData data, StickData preData) {
                            showKLineTitle(data ,preData);
                        }
                    });
                }
            });

        }
    }

    //分时线
    @Override
    public void onReceive(List<CMinute> list, String lastSettle) {
        Log.e("hurui" , "CMinute : " + list.size());
        if(fenshiView != null && fenshiView.getVisibility() == View.VISIBLE){
            double lastSettleValue = StringConvertNumber.parseDouble(lastSettle);
            final FenshiParam fenshiParam = new FenshiParam();
            fenshiParam.setDuration("9:30-11:30|13:00-15:00");
            minuteData.setParam(fenshiParam);
            minuteData.getParam().setLast(lastSettleValue);
            if (list.size() >= 1) {
                minuteData.getParam().setUntil(list.get(list.size() - 1).getTime());
            }
            minuteData.setData(list);
            fenshiView.setDataAndInvalidate(minuteData, instType);
            //显示 坐标位置
            fenshiView.setUsedViews(crossView, msgText);
            fenshiView.setOnCrossListener(new FenshiView.OnCrossListener() {
                @Override
                public void onDismiss() {
                    hideMinuteTitle();
                }

                @Override
                public void onShow(CMinute cMinute, double lastSettle) {
                    showMinuteTitle(cMinute, lastSettle);
                }
            });
        }
    }

    public class QueryTdLoginStateTask extends AsyncTask<Void, Void, TDLogin> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected TDLogin doInBackground(Void... params) {

            try {
                TDLogin tdLoginState = HomeService.getInstance().getTDLoginState();
                if (tdLoginState != null) {
                    return tdLoginState;
                }
            } catch (ServerException e) {
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_SERVER_ERROR_CODE, e.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_ERROR_CODE, null);
            }

            return null;
        }

        @Override
        protected void onPostExecute(TDLogin tdLogin) {
            super.onPostExecute(tdLogin);
            if (tdLogin == null) {
                return;
            }
            if (tdLogin.getStatus()) {
                QuickMakeOrderFragment dialog = QuickMakeOrderFragment.newInstance(instType);
                FragmentManager fm = getActivity().getSupportFragmentManager();
                fm.beginTransaction()
                        .add(R.id.quotation_chart_layout, dialog)
                        .addToBackStack(null)
                        .commit();
            } else {
                ActivityUtils.gotoTradeLogin(getActivity());
            }
        }
    }

    public boolean handleMessage(Message msg) {
        int type = msg.what;
        switch (type) {
            case NetWorkConstant.NETWORK_ERROR_CODE:
                showToastMessage(R.string.network_error, Toast.LENGTH_LONG);
                break;
            case NetWorkConstant.NETWORK_SERVER_ERROR_CODE:
                String errorMessage = (String) msg.obj;
                showToastMessage(errorMessage, Toast.LENGTH_LONG);
                break;
        }

        return true;
    }

    private void sendNetworkErrorMessage(int type, String errorMessage) {
        Message message = handler.obtainMessage();
        message.what = type;
        if (!TextUtils.isEmpty(errorMessage)) {
            message.obj = errorMessage;
        }
        handler.sendMessage(message);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFiveRangeEventBus(FiveRangeMessageEvent event) {
        if (event.getType() == Market.Category.QUOTEFIVERANGE && event.getIdentification().getInstType() == instType) {
            fillFiveRangeData(event.getQuoteFiveRange());
        }
    }

    public void setItemValueAndColor(TextView item, String buyPrice, double lastSettle) {
        item.setText(buyPrice);
        double price = StringConvertNumber.parseDouble(buyPrice);
        if (lastSettle > price) {
            item.setTextColor(getResources().getColor(R.color.color_green));
        } else if (lastSettle == price) {
            item.setTextColor(getResources().getColor(R.color.td_color_gray_two));
        } else {
            item.setTextColor(getResources().getColor(R.color.color_red_two));
        }
    }

    private void fillFiveRangeData(Market.QuoteFiveRange quoteFiveRange) {
        double lastSettle = StringConvertNumber.parseDouble(quoteFiveRange.getLastSettle());
        setItemValueAndColor(buyFive, quoteFiveRange.getBuyPrice5(), lastSettle);
        setItemValueAndColor(buyFour, quoteFiveRange.getBuyPrice4(), lastSettle);
        setItemValueAndColor(buyThree, quoteFiveRange.getBuyPrice3(), lastSettle);
        setItemValueAndColor(buyTwo, quoteFiveRange.getBuyPrice2(), lastSettle);
        setItemValueAndColor(buyOne, quoteFiveRange.getBuyPrice1(), lastSettle);

        buyFiveVolume.setText(quoteFiveRange.getBuyVolume5() + "");
        buyFourVolume.setText(quoteFiveRange.getBuyVolume4() + "");
        buyThreeVolume.setText(quoteFiveRange.getBuyVolume3() + "");
        buyTwoVolume.setText(quoteFiveRange.getBuyVolume2() + "");
        buyOneVolume.setText(quoteFiveRange.getBuyVolume1() + "");

        setItemValueAndColor(soldFive, quoteFiveRange.getSellPrice5(), lastSettle);
        setItemValueAndColor(soldFour, quoteFiveRange.getSellPrice4(), lastSettle);
        setItemValueAndColor(soldThree, quoteFiveRange.getSellPrice3(), lastSettle);
        setItemValueAndColor(soldTwo, quoteFiveRange.getSellPrice2(), lastSettle);
        setItemValueAndColor(soldOne, quoteFiveRange.getSellPrice1(), lastSettle);

        soldFiveVolume.setText(quoteFiveRange.getSellPolume5() + "");
        soldFourVolume.setText(quoteFiveRange.getSellPolume4() + "");
        soldThreeVolume.setText(quoteFiveRange.getSellPolume3() + "");
        soldTwoVolume.setText(quoteFiveRange.getSellPolume2() + "");
        soldOneVolume.setText(quoteFiveRange.getSellPolume1() + "");
    }

    private void showStateTipView(String text) {
        stateTipLayout = (LinearLayout) LayoutInflater.from(getActivity()).inflate(
                R.layout.state_tip_dialog, null);
        TextView stateTipText = (TextView) stateTipLayout.findViewById(R.id.state_tip_txt);
        stateTipText.setText(text);
        PopupWindow stateTipWindow = new PopupWindow(getActivity());
        stateTipWindow.setBackgroundDrawable(new BitmapDrawable());
        stateTipWindow.setOutsideTouchable(true);
        stateTipWindow.setFocusable(true);
        stateTipWindow
                .setWidth(getActivity().getWindowManager().getDefaultDisplay().getWidth() / 2);
        stateTipWindow.setHeight(200);
        stateTipWindow.setContentView(stateTipLayout);
        stateTipWindow.showAsDropDown(currentTradeState, 0, 0);
    }

    public void showMorePopupWindow() {
        layout = (LinearLayout) LayoutInflater.from(getActivity()).inflate(
                R.layout.popupwindow_dialog, null);
        lvPopup = (ListView) layout.findViewById(R.id.lv_dialog);
        final String[] more = getResources().getStringArray(R.array.kline_minute_title);
        lvPopup.setAdapter(new ArrayAdapter<>(getActivity(),
                R.layout.popupwindow_dialog_item, R.id.tv_text, more));

        popupWindow = new PopupWindow(layout, getActivity().getWindowManager().getDefaultDisplay().getWidth() / 6, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.getContentView().measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        popupWindow.showAsDropDown(kminuteLayout, 0, 0);//需要指定Gravity，默认情况是center.
        lvPopup.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parentView, View view, int position,
                                    long id) {
                txtKminute.setText(more[position]);
                selectTab(5);
                refreshPage(more[position]);
                if (popupWindow != null) {
                    popupWindow.dismiss();
                    popupWindow = null;
                }
            }
        });
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                ActivityUtils.backgroundAlpha(getActivity(), 1f);
            }
        });
    }

    public void refreshPage(String title) {
        switch (title) {
            case "1分":
                mCategory = Market.Category.KLINEMIN1PAGE;
                break;
            case "5分":
                mCategory = Market.Category.KLINEMIN5PAGE;
                break;
            case "15分":
                mCategory = Market.Category.KLINEMIN15PAGE;
                break;
            case "30分":
                mCategory = Market.Category.KLINEMIN30PAGE;
                break;
            case "60分":
                mCategory = Market.Category.KLINEMIN60PAGE;
                break;
            case "240分":
                mCategory = Market.Category.KLINEMIN240PAGE;
                break;
        }
        MarketManager.getInstance().sendRequestMsg(instType, mCategory);
    }

    public void showKLineTitle(StickData data, StickData preData) {
        if(kLineDataLayout == null){
            return;
        }
        kLineDataLayout.setVisibility(View.VISIBLE);
        vpTitleLayout.setVisibility(View.GONE);
        setItemValueAndColor(openPrice, data.getOpen(), preData.getClose());
        setItemValueAndColor(closePrice, data.getClose(), preData.getClose());
        setItemValueAndColor(khighestPrice, data.getHigh(), preData.getClose());
        setItemValueAndColor(klowestPrice, data.getLow(), preData.getClose());
        kVolume.setText(StringConvertNumber.volumeToString(data.getCount()));
        double balance = MathUtils.decimalReduceKeepTwoPlaces(data.getClose(), preData.getClose());
        if (instType == Market.InstType.AG_TD) {
            setItemValueAndColor(averagePrice, MathUtils.ADivideB(data.getMoney(), data.getCount(), 0), preData.getClose());
            if (balance > 0) {
                setItemValueAndColorBySymbol(kquota, "+" + MathUtils.doubleToInt(balance), "+" + MathUtils.doubleToInt(balance));
            } else {
                setItemValueAndColorBySymbol(kquota, MathUtils.doubleToInt(balance), MathUtils.doubleToInt(balance));
            }
        } else {
            if (balance > 0) {
                setItemValueAndColorBySymbol(kquota, "+" + MathUtils.doubleKeepToDecimal(balance), "+" + MathUtils.doubleToInt(balance));
            } else {
                setItemValueAndColorBySymbol(kquota, MathUtils.doubleKeepToDecimal(balance), MathUtils.doubleToInt(balance));
            }
            if (instType == Market.InstType.AU_TD) {
                setItemValueAndColor(averagePrice, MathUtils.ADivideB(data.getMoney(), data.getCount() * 1000, 2), preData.getClose());
            } else {
                setItemValueAndColor(averagePrice, MathUtils.ADivideB(data.getMoney(), data.getCount() * 100, 2), preData.getClose());
            }
        }

        String rate = MathUtils.doubleADivideB(Double.parseDouble(MathUtils.decimalMultiplyKeepTwoPlaces(balance, 100)), preData.getClose());
        if (Double.parseDouble(rate) >= 0) {
            setItemValueAndColorBySymbol(kRate, "+" + rate + "%", "+" + rate + "%");
        } else {
            setItemValueAndColorBySymbol(kRate, rate + "%", rate + "%");
        }
    }

    public void hideKLineTitle() {
        kLineDataLayout.setVisibility(View.GONE);
        vpTitleLayout.setVisibility(View.VISIBLE);
    }

    public void showMinuteTitle(CMinute cMinute, Double lastSettle) {
        minuteDataLayout.setVisibility(View.VISIBLE);
        vpTitleLayout.setVisibility(View.GONE);
        minuteTime.setText(cMinute.getTimeStr());
        if (cMinute.getRate() == null) {
            cMinute.setRate("0.00");
        }
        minuteVolume.setText("成交量：" + cMinute.getCount() + "");
        setItemValueAndColorBySymbol(minutePriceRate, cMinute.getPrice() + "(" + cMinute.getRate() + "%)", cMinute.getRate());
        if (instType == Market.InstType.AG_TD) {
            minutePriceRate.setText(MathUtils.doubleToInt(cMinute.getPrice()) + "(" + cMinute.getRate() + "%)");
            setItemValueAndColor(minuteAveragePrice, cMinute.getAverage(), lastSettle);
        } else {
            setItemValueAndColor(minuteAveragePrice, cMinute.getAverage(), lastSettle);
            minutePriceRate.setText(MathUtils.doubleKeepToDecimal(cMinute.getPrice()) + "(" + cMinute.getRate() + "%)");
        }

    }

    public void hideMinuteTitle() {
        minuteDataLayout.setVisibility(View.GONE);
        vpTitleLayout.setVisibility(View.VISIBLE);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onQuoteDynaEventBus(DynaMessageEvent event) {

        if (event.getType() == Market.Category.QUOTEDYNA) {
            if (!isVisible()) {
                return;
            }
            if (event.getIdentification().getInstType() == instType) {
                fillMarketData(event.getQuoteDyna());
            }
        }
    }

    private void fillMarketData(Market.QuoteDyna quoteDyna) {
        if (!isVisible()) {
            return;
        }
        if(yesterdayClosePrice == null){
            return;
        }
        double lastSettle = StringConvertNumber.parseDouble(quoteDyna.getLastSettle());
        yesterdayClosingPrice = lastSettle;
        setItemValueAndColor(highestPrice, StringConvertNumber.parseDouble(quoteDyna.getHighestPrice()), lastSettle);
        yesterdayClosePrice.setText(quoteDyna.getLastClose());
        yesterdayEndPrice.setText(quoteDyna.getLastSettle());
        setItemValueAndColor(minimumPrice, StringConvertNumber.parseDouble(quoteDyna.getLowestPrice()), lastSettle);
        setItemValueAndColor(todayOpenPrice, StringConvertNumber.parseDouble(quoteDyna.getOpenPrice()), lastSettle);
        totalQuantity.setText(StringConvertNumber.volumeToString(quoteDyna.getVolume()));
        setItemValueAndColor(currentPrice, StringConvertNumber.parseDouble(quoteDyna.getLastPrice()), lastSettle);
        setItemValueAndColorBySymbol(txtRate, quoteDyna.getUpDown() + "  " + quoteDyna.getUpDownRate(), quoteDyna.getUpDownRate());
        txtCurrentTime.setText(quoteDyna.getTime());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onQuoteInstEventBus(InstMessageEvent event) {
        if (event.getType() == Market.Category.QUOTEINST) {
            if (isVisible()) {
                fillInstData(event.getQuoteInst());
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLongConnectionFailEventBus(ConnectionFailEvent event) {
        if (isVisible()) {
            tipLayout.setVisibility(View.VISIBLE);
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLongConnectionSuccessEventBus(ConnectionSuccessEvent event) {
        if(isVisible()){
            if (tipLayout != null) {
                tipLayout.setVisibility(View.GONE);
            }
        }
        selectTab(cur_id);
    }

    /*判断合约状态*/
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void fillInstData(Market.QuoteInst quoteInst) {

        if(currentTradeState == null){
            return;
        }
        if (quoteInst.getState() == Market.State.TRADE_INVALID || quoteInst.getState() == Market.State.TRADE_CLOSE || quoteInst.getState() == Market.State.TRADE_REST) {
            tradeState = false;
            currentTradeState.setBackground(getActivity().getResources().getDrawable(R.drawable.trade_state_abnormal));
            currentTradeState.setTextColor(getActivity().getResources().getColor(R.color.td_color_gray_three));
        } else if (quoteInst.getState() == Market.State.TRADE_ING || quoteInst.getState() == Market.State.TRADE_START) {
            tradeState = true;
            currentTradeState.setBackground(getActivity().getResources().getDrawable(R.drawable.trade_state_normal));
            currentTradeState.setTextColor(getActivity().getResources().getColor(R.color.color_gold));
        }
        currentTradeState.setText(quoteInst.getDescription());
    }

    public void setItemValueAndColorBySymbol(TextView item, String value, String value1) {
        item.setText(value);
        if ("+".equals(value1.substring(0, 1))) {
            item.setTextColor(getResources().getColor(R.color.color_red_two));
        } else if ("-".equals(value1.substring(0, 1))) {
            item.setTextColor(getResources().getColor(R.color.color_green));
        } else {
            item.setTextColor(getResources().getColor(R.color.td_color_gray_two));
        }
    }

    public void setItemValueAndColor(TextView item, double buyPrice, double lastSettle) {
        if (item == null) {
            return;
        }
        if (instType == Market.InstType.AG_TD) {
            item.setText(MathUtils.doubleToInt(buyPrice));
        } else {
            item.setText(MathUtils.doubleKeepToDecimal(buyPrice));
        }
        if (lastSettle > buyPrice) {
            item.setTextColor(getResources().getColor(R.color.color_green));
        } else if (lastSettle == buyPrice) {
            item.setTextColor(getResources().getColor(R.color.td_color_gray_two));
        } else {
            item.setTextColor(getResources().getColor(R.color.color_red_two));
        }

    }


    public class QuerySwitchStateTask extends AsyncTask<Void, Void, Switch> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected Switch doInBackground(Void... params) {
            Switch switchValue = null;
            try {
                switchValue = TradeService.getInstance().getSwitch();
            } catch (ServerException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_ERROR_CODE, null);
            }

            return switchValue;
        }

        @Override
        protected void onPostExecute(Switch switchValue) {
            super.onPostExecute(switchValue);
            if (switchValue == null) {
                return;
            }
            if (!switchValue.isSwitchFlag()) {
                Intent intent = new Intent(getContext(), TDMainActivity.class);
                intent.putExtra(IntentConstant._TYPE, "trade");
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                finishActivity();
            } else {
                if (!MyService.getInstance().isLogin()) {
                    Intent intent = new Intent(getActivity(), UserActivity.class);
                    startActivity(intent);
                } else {
                    new QueryTdLoginStateTask().execute(AsyncTask.TYPE_NET);
                }
            }
        }
    }


    private static class MyHandler extends Handler {
        private final WeakReference<QuotationChartFragment> mFragment;

        public MyHandler(QuotationChartFragment fragment) {
            mFragment = new WeakReference<QuotationChartFragment>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            if (mFragment.get() == null) {
                return;
            }
            mFragment.get().handleMessage(msg);
        }
    }
}
